package com.chis.client;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.Map;

/**
 *
 * @Description
 * @Company zwx
 * @author wlj
 * @version 2019年12月20日
 */
public class HttpClientUtil {
    private static final int TIMEOUT_SECONDS = 10*1000;
    //证书密码
    private final static String PFX_PWD = "nclient";
    //tls的协议版本
    private final static String TLS_VERSION = "TLSv1";
    private static CloseableHttpClient httpClient;

    static {
        try{
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            InputStream instream = HttpClientUtil.class.getResourceAsStream( "/nclient.pfx");
            try {
                // 这里就指的是KeyStore库的密码
                keyStore.load(instream, PFX_PWD.toCharArray());
            } finally {
                instream.close();
            }

            SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, PFX_PWD.toCharArray()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext
                    , new String[] { TLS_VERSION }
                    , null
                    , NoopHostnameVerifier.INSTANCE);


            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", sslsf)
                    .build();
            PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry);
            connectionManager.setMaxTotal(888);
            //默认每路由最高并发，具体依据业务来定
            connectionManager.setDefaultMaxPerRoute(60);

            RequestConfig HttpRequestConfig = RequestConfig.custom()
                    .setSocketTimeout( TIMEOUT_SECONDS)
                    .setConnectionRequestTimeout( TIMEOUT_SECONDS)
                    .setConnectTimeout( TIMEOUT_SECONDS).build();
            httpClient = HttpClients.custom()
                    .setDefaultRequestConfig( HttpRequestConfig)
                    .setConnectionManager( connectionManager)
                    .build();
        }catch ( Exception e){
            e.printStackTrace();
        }
    }

    public static String postRequest( String url, Map<String,String> headMap,
                                      Map<String,String> bodyMap, String bodyJson)throws Exception{
        RequestBuilder requestBuilder= RequestBuilder.post( url);
        if( null!= headMap){
            for( Map.Entry<String,String> entry: headMap.entrySet()){
                requestBuilder.addHeader( entry.getKey(), entry.getValue());
            }
        }
        if( null!= bodyMap){
            for( Map.Entry<String,String> entry: bodyMap.entrySet()){
                requestBuilder.addParameter( entry.getKey(), entry.getValue());
            }
        }
        if(StringUtils.isNotBlank( bodyJson)){
            requestBuilder.setEntity( new StringEntity( bodyJson, ContentType.APPLICATION_JSON));
        }

        HttpUriRequest request= requestBuilder.build();
        CloseableHttpResponse response= httpClient.execute( request);
        return toString( response);
    }
    public static String postRequest( String url, String bodyJson)throws Exception{
        RequestBuilder requestBuilder= RequestBuilder.post( url);

        if(StringUtils.isNotBlank( bodyJson)){
            requestBuilder.setEntity( new StringEntity( bodyJson, ContentType.APPLICATION_JSON));
        }

        HttpUriRequest request= requestBuilder.build();
        CloseableHttpResponse response= httpClient.execute( request);
        return toString( response);
    }
    private static String toString( CloseableHttpResponse response)throws Exception{
        try{
            if(HttpStatus.SC_OK== response.getStatusLine().getStatusCode()){
                return EntityUtils.toString( response.getEntity());
            }else{
                System.out.println("http error code:"+ response.getStatusLine().getStatusCode());
                return null;
            }
        }finally {
            if( null!= response){
                EntityUtils.consume( response.getEntity());
            }
        }
    }

}

